Java进阶-Vector 集合源码分析

  1. 底层也是一个数组

  2. 初始化容量:10

  3. 怎么扩容?

    • 扩容之后是原容量的 2 倍

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      private Object[] grow(int minCapacity) {
      int oldCapacity = elementData.length;
      int newCapacity = ArraysSupport.newLength(oldCapacity,
      minCapacity - oldCapacity, /* minimum growth */
      capacityIncrement > 0 ? capacityIncrement : oldCapacity /* preferred growth */);
      return elementData = Arrays.copyOf(elementData, newCapacity);
      }
      /**
      * The amount by which the capacity of the vector is automatically
      * incremented when its size becomes greater than its capacity. If
      * the capacity increment is less than or equal to zero, the capacity
      * of the vector is doubled each time it needs to grow.
      *
      * @serial
      */
      protected int capacityIncrement;
  4. ArrayList 集合扩容是原容量的 1.5 倍

  5. Vector 中所有的方法都是线程同步的,都带有 synchronized 关键字,是线程安全的,效率比较低,使用较少了

  6. 怎么将一个线程不安全的 ArrayList 集合转换成线程安全的呢?

    • 使用集合工具类:java.util.Collections;
    • 注意:
      • java.util.Collection 是集合接口
      • java.util.Collections 是集合工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

public class VectorTest01 {

public static void main(String[] args) {
// 创建一个 Vector 集合
Vector vector = new Vector();

// 添加元素
// 默认容量 10 个
vector.add(1);
vector.add(2);
vector.add(3);
vector.add(4);
vector.add(5);
vector.add(6);
vector.add(7);
vector.add(8);
vector.add(9);
vector.add(10);

// 满了之后扩容
vector.add(11);

for (Object object : vector) {
System.out.println(object);
}

// 非线程安全
List myList = new ArrayList();

// 变成线程安全
Collections.synchronizedList(myList);

// myList集合就是线程安全的了
myList.add("111");
myList.add("222");
myList.add("333");

for (Object object : myList) {
System.out.println(object);
}
}
}